package com.ly.sms;

import com.ly.sms.model.RspEnum;
import com.ly.sms.model.SmsRequest;
import com.ly.sms.model.SmsResp;
import com.ly.sms.service.SmsRsp;
import com.ly.sms.utils.HttpUtils;
import com.ly.sms.utils.HttpUtils.HttpResult;
import com.ly.sms.utils.JsonUtils;
import com.ly.sms.utils.LoggerBuilder;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author ly
 * @Date 2022-03-27 12:35
 */
public class Test {

  public static Logger fileLogger = new LoggerBuilder().getLogger(
      "C:\\Users\\liyong\\Documents\\WeChat Files\\wxid_ok33zzoisxy021\\FileStorage\\File\\2022-03",
      "123");

  private static Executor pool = Executors.newFixedThreadPool(15);

  private static final String register_url = "http://127.0.0.1:8080/auth/user/register";
  private static final String login_url = "http://127.0.0.1:8080/auth/user/login";
  private static final String logout_url = "http://127.0.0.1:8080/auth/user/logout";
  private static final String sendMsg_url = "http://127.0.0.1:8080/directmessage?tels=13580549835&qos=1&userName=admin&sessionId=e8c7bf0a-cbcc-4840-9a4a-ddc3daa7456b";

  private static volatile AtomicInteger call_add = new AtomicInteger(0);

  private static volatile AtomicInteger result1 = new AtomicInteger(0);
  private static volatile AtomicInteger result2 = new AtomicInteger(0);
  private static volatile AtomicInteger result3 = new AtomicInteger(0);

  private static volatile AtomicInteger total1 = new AtomicInteger(0);
  private static volatile AtomicInteger total2 = new AtomicInteger(0);
  private static volatile AtomicInteger total3 = new AtomicInteger(0);

  public static void main(String[] args) {
    // 这个是测试类，仅做压测，用户注册，登录，登出动作不涉及

    Long callNumber = 13800000000L;

    LocalDateTime begin = LocalDateTime.now();
    LocalDateTime end = begin.plusMinutes(15);

    for (int j = 0; j <= 14; j++) {

      pool.execute(() -> {
        while (true) {
          if (LocalDateTime.now().isAfter(end)) {
            break;
          }
          try {
            Thread.sleep(1000L);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          int i = new Random().nextInt(3) + 1;

          SmsRequest request = new SmsRequest();

          request.setQos(i + "");
          request.setSessionId("6babaf5c-1bfa-411e-91cb-9e82bcbcc220");
          request.setTels((callNumber + call_add.getAndIncrement()) + "");
//          request.setTels((callNumber + ""));
          request.setUserName("admin");
          request.setContent("内容");
          request.setTitle("标题");

          long beginTime = System.currentTimeMillis();
          SmsResp smsResp = doSendMsg(request);
          long endTime = System.currentTimeMillis();

          fileLogger.info("发送结果 {},{}, {}, {}", callNumber, i, smsResp.getCode(), endTime - beginTime);

          if (RspEnum.SUCCESS.getCode().equals(smsResp.getCode())) {
            switch (i) {
              case 1:
                result1.getAndIncrement();
                break;
              case 2:
                result2.getAndIncrement();
                break;
              case 3:
                result3.getAndIncrement();
                break;
            }
          }

          switch (i) {
            case 1:
              total1.getAndIncrement();
              break;
            case 2:
              total2.getAndIncrement();
              break;
            case 3:
              total3.getAndIncrement();
              break;
          }

        }
      });
    }

    System.out.println("准备结束............................");
    try {
      Thread.sleep(5000L);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println(".........结束............................");

    System.out
        .println("result" + "1:" + result1.get() + ",2:" + result2.get() + ",3:" + result3.get());
    System.out.println("total" + "1:" + total1.get() + ",2:" + total2.get() + ",3:" + total3.get());


  }


  private static SmsResp doSendMsg(SmsRequest request) {
    Map<String, String> map2 = new HashMap<>();
    map2.put("title", request.getTitle());
    map2.put("content", request.getContent());

    Map<String, String> header = new HashMap<>();
    header.put("Content-Type", "application/json");

    try {
      String url = "http://127.0.0.1:8080/directmessage?"
          + "tels=" + request.getTels() + "&qos=" + request.getQos() + "&userName=" + request
          .getUserName() + "&sessionId=" + request.getSessionId();
      System.out.println("url:" + url);
      HttpResult post = HttpUtils
          .getInstance().post(url, Charset.defaultCharset(), JsonUtils.toJson(map2), header, 5000);

      if (post.getStatusCode() == 200 && post.getContent() != null) {

        Map<String, String> smsRsp = JsonUtils.fromJson(post.getContent(), HashMap.class);

        if (StringUtils.equals("200", smsRsp.get("code"))) {
          return new SmsResp(RspEnum.SUCCESS.getCode(), RspEnum.SUCCESS.getMsg());
        }
        return new SmsResp(RspEnum.SEND_MSG_ERROR.getCode(),
            RspEnum.SEND_MSG_ERROR.getMsg() + ":" + smsRsp.get("message"));
      }

    } catch (URISyntaxException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return new SmsResp(RspEnum.SEND_MSG_ERROR.getCode(), RspEnum.SEND_MSG_ERROR.getMsg());
  }

}
